<template>
    <div>
        <Row style="margin-top: 40px"  type="flex" justify="center" class="code-row-bg" align="middle">
            <i-col span="5" class="login">
                <Card class="login_card">
                    <Tooltip content="密码重置" placement="top-start">
                        <a @click="clickRestPwdHandle">十方海尘众生卷</a>
                    </Tooltip>
                    <div style="text-align:center">
                        <Form ref="formInline" :model="formInline" :rules="ruleInline">
                            <FormItem prop="username">
                                <Input type="text" v-model="formInline.username" placeholder="用户"/>
                                <Icon type="ios-person-outline" slot="prepend"/>
                            </FormItem>
                            <FormItem prop="password">
                                <Input type="password" v-model="formInline.password" placeholder="密码"/>
                                    <Icon type="ios-lock-outline" slot="prepend"/>
                            </FormItem>
                    
                            <Row type="flex" justify="end" align="middle">
                                <i-col span="12" class="login_card_rememberMe">
                                    <Button type="primary" shape="circle" icon="ios-add-circle-outline" @click="registerButHandleClick">
                                        注册
                                    </Button>
                                </i-col>
                                <i-col span="12" class="login_card_button">
                                    <Button type="success" shape="circle" icon="md-power" :loading="loading" @click="loginButHandleClick('formInline')">
                                        登录
                                    </Button>
                                </i-col>
                            </Row>
                        </Form>
                    </div>
                </Card>
            </i-col>
        </Row>
        <TheRegisterModal :isShowRegisterModal="isShowRegisterModal" @close-register-modal="closeRegisterModal"></TheRegisterModal>
        <TheRestPwdModal :isShowRestPwdModal="isShowRestPwdModal" @close-restpwd-modal="closeRestPwdModal"></TheRestPwdModal>
    </div>
</template>

<script lang="tsx">
import { Component, Vue } from "vue-property-decorator"
import qs from 'qs'
import { OAUTH_TOKEN,LOGOUT } from '@/store/modules/app/keys'
import state from '@/store/modules/app/state'
import TheRegisterModal from './TheRegisterModal.vue'
import TheRestPwdModal from './TheRestPwdModal.vue'
import cryptoJs from 'crypto-js';
import { Base64 } from 'js-base64';

@Component({
    components:{
        TheRegisterModal,
        TheRestPwdModal
    }
})
export default class TheLogin extends Vue {
    formInline = {
            username: "",
            password: ""
    }
    ruleInline = {
        username:[
            { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入密码.', trigger: 'blur' },
            { type: 'string', min: 6, message: '密码长度大于等于六位', trigger: 'blur' }
        ]
    }
    isShowRegisterModal = false;
    isShowRestPwdModal = false;
    loading = false;

    async loginButHandleClick(formInline: any) {
        this.loading = true;
        (this.$refs[formInline] as any).validate(async (valid: any)=>{
            if(valid){
                const username = this.formInline.username;
                const password = this.formInline.password;

                const key = this.generatekey();
                const base64Username = Base64.encode(username);
                const base64Password = Base64.encode(password);

                const desEncUsername = this.encryptDes(base64Username,key);
                const desEncPassword = this.encryptDes(base64Password,key);

                const checkBit = this.generateCheckBit(username + password + key);
                const formData = {
                    username: Base64.encode(desEncUsername + key),
                    password: Base64.encode(desEncPassword),
                    checkBit: checkBit,
                    grant_type: 'password'
                }
                await this.$store.dispatch(OAUTH_TOKEN, qs.stringify(formData))
                if(state.isHasLogin!=""){
                    this.isLoginFaile()
                    return;
                }
                if(state.access_token && state.isHasLogin == ""){
                    this.$router.push({name: 'main'});
                }
            }
        });
        this.loading = false;
    }
    registerButHandleClick(){
        this.isShowRegisterModal = true;
    }
    closeRegisterModal(){
        this.isShowRegisterModal = false;
    }
    closeRestPwdModal(){
        this.isShowRestPwdModal = false;
    }
    clickRestPwdHandle(){
        this.isShowRestPwdModal = true;
    }
    isLoginFaile(){
        this.$Modal.confirm({
            title: "登录失败！",
            content: "用户已登录，是否强制下线?",
            okText: "强制下线",
            cancelText: "取消",
            loading: true,
            onOk: async ()=>{
                const str = state.isHasLogin;
                const accessToken = str?.substring(str.length-36,str.length);
                if(accessToken){
                    sessionStorage.setItem("dev:access_token",accessToken)
                }
                const promise = await this.$store.dispatch(LOGOUT);
                if(promise){
                    this.$Message.success("强制退出成功！");
                }
                this.$Modal.remove();
                this.loading = false
            },
            onCancel:()=>{
                this.$Modal.remove();
                this.loading = false
            }
        });
    }
    //随机生成指定数量的32进制key
    generatekey(): string {
        const num = 32;
        const library = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let key = "";
        for (let i = 0; i < num; i++) {
            const randomPoz = Math.floor(Math.random() * library.length);
            key += library.substring(randomPoz, randomPoz + 1);
        }
        return key;
    }
    //DES加密
    encryptDes(message: string, key: string): string {
        const keyHex = cryptoJs.enc.Utf8.parse(key)
        const option = { mode: cryptoJs.mode.ECB, padding: cryptoJs.pad.Pkcs7 }
        const encrypted = cryptoJs.DES.encrypt(message, keyHex, option).toString()
        return encrypted
    }
    generateCheckBit(str: string){
        let sum = 0;
        for(let i=0; i<str.length;i++ ){
            let k = str.charCodeAt(i);
            sum = sum + k;
        }
        return sum;
    }
}
</script>

<style scoped>
.login_card {
    text-align: center;
    background:#f8f8f9;
    border-radius: 48px;
}
.login {
    background:  #c5c8ce!important;
}
.login_card_rememberMe {
    text-align: right;
    padding-right: 25px;
}
.login_card_button {
    text-align: left;
    padding-left: 25px;
}
</style>
